package top.huxy.boot.service.impl;

import com.sun.management.OperatingSystemMXBean;
import org.springframework.stereotype.Service;
import top.huxy.boot.service.IMonitorService;
import top.huxy.boot.util.obj.MonitorInfoBean;

import java.lang.management.ManagementFactory;

/**
 * @Classname MonitorServiceImpl
 * @Description MonitorServiceImpl
 * @Date 2021/10/1 14:32
 * @Created by huxy
 */
@Service
public class MonitorServiceImpl implements IMonitorService {

    //可以设置长些，防止读到运行此次系统检查时的cpu占用率，就不准了
    private static final int CPUTIME = 5000;

    private static final int PERCENT = 100;

    private static final int FAULTLENGTH = 10;

    /**
     * 获得当前的监控对象.
     *
     * @return 返回构造好的监控对象
     * @throws Exception
     * @author GuoHuang
     */

    public MonitorInfoBean getMonitorInfoBean()  {
        int kb = 1024;

        // 可使用内存

        long totalMemory = Runtime.getRuntime().totalMemory() / kb;

        // 剩余内存

        long freeMemory = Runtime.getRuntime().freeMemory() / kb;

        // 最大可使用内存

        long maxMemory = Runtime.getRuntime().maxMemory() / kb;

        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory

                .getOperatingSystemMXBean();

        // 操作系统

        String osName = System.getProperty("os.name");

        // 总的物理内存

        long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;

        // 剩余的物理内存

        long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;

        // 已使用的物理内存

        long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb

                .getFreePhysicalMemorySize())

                / kb;

        // 获得线程总数

        ThreadGroup parentThread;

        for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; ) {
            parentThread = parentThread.getParent();
        }

        int totalThread = parentThread.activeCount();

        // 构造返回对象

        MonitorInfoBean infoBean = new MonitorInfoBean();

        infoBean.setFreeMemory(freeMemory);

        infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);

        infoBean.setMaxMemory(maxMemory);

        infoBean.setOsName(osName);

        infoBean.setTotalMemory(totalMemory);

        infoBean.setTotalMemorySize(totalMemorySize);

        infoBean.setTotalThread(totalThread);

        infoBean.setUsedMemory(usedMemory);

        return infoBean;

    }
}